<?php
defined('SYS_RUN') or exit();

class Cli {

    private $_args;

    private $_params = array();

    private $_class = '';

    private $_method = '';

    const METHOD_PATTERN = 'action%s';

    function __construct($args) {
        $this->_args = $args[0];
        unset($this->_args[0]);
        if(isset($this->_args[1]))
            $this->_class = $this->_args[1];
        else throw new CliException('Incorrect class name! '.$this->_getExample(), true);
        unset($this->_args[1]);
        if(isset($this->_args[2]))
            $this->_method = sprintf(self::METHOD_PATTERN, ucfirst($this->_args[2]));
        else throw new CliException('Incorrect method name! '.$this->_getExample(), true);
        unset($this->_args[2]);

        if(count($this->_args) > 0)
            $this->_params = $this->_parseArgs($this->_args);
    }

    public function runHandler() {
        $command = Command::get($this->_class);
        $method = $this->_method;
        $command->cli = $this;
        $command->$method($this->_params);
    }

    public function write($string) {
        fwrite(STDOUT, $string."\n");
    }

    private function _getExample() {
        $example = PHP_EOL.'           Example: {runner} {class name} {method name} --{param name 1}={param value} --{param name2}={param value}';
        $example .= PHP_EOL.'           php worker start --interval=30';
        return $example;
    }

    private function _parseArgs($args) {
        $params = array();
        foreach($args as $arg) {
            $aArg = $this->_checkParseArg($arg);
            $params[$aArg['name']] = $aArg['value'];
        }
        return $params;
    }

    private function _checkParseArg($arg) {
        $result = array();
        $sArg = str_replace('--', '', $arg);
        $aArg = explode('=', $sArg);
        if(count($aArg) == 0) {
            throw new CliException('Incorrect param format:'.$arg.$this->_getExample(), true);
        }
        $result['name'] = $aArg[0];
        $result['value'] = (isset($aArg[1]))?$aArg[1]:'';
        return $result;
    }
}